<template>
	<view class="ithui-content">
		<view class="upload">
			<text class="upload-tip">请拍摄并上传你的有效身份证照片</text>
			<view class="upload-item">
				<u-upload @afterRead="afterRead($event,'zm')" :fileList="uploadList['zm']"
					@delete="deletePic($event,'zm')" name="uploadA" multiple :maxCount="1" width="160" height="100">
					<image :src="sfzzm" style="width: 160px;height: 100px;">
					</image>
				</u-upload>
				<text class="title">身份证正面</text>
			</view>
			<view class="upload-item">
				<u-upload @afterRead="afterRead($event,'fm')" :fileList="uploadList['fm']"
					@delete="deletePic($event,'fm')" name="uploadB" multiple :maxCount="1" width="160" height="100">
					<image :src="sfzfm" style="width: 160px;height: 100px;">
					</image>
				</u-upload>
				<text class="title">身份证反面</text>
			</view>
		</view>
		<view class="confirm">

			<view class="mt-20 b-line tips">请确认你的身份信息：</view>
			<view style="margin-top: 100rpx;" v-if="loading"><up-loading-icon :vertical="true"
					text="识别中"></up-loading-icon></view>
			<view v-else>
				<view class="confirm-item">
					<view class="key">姓名</view>
					<text class="val">{{userInfo.name||'未上传'}}</text>
					<!-- <u-input v-model="data.carCode1" border="none" placeholder="请输入"
						input-align="right"></u-input> -->
				</view>
				<view class="mt-20 confirm-item">
					<view class="key">身份证号</view>
					<text class="val">{{userInfo.number||'未上传'}}</text>
				</view>
				<view class="mt-20 confirm-item">
					<view class="key">有效期</view>
					<text class="val">{{userInfo.validTo||'未上传'}}</text>
				</view>
				<view class="submit">
					<u-button @click="nextStep" shape="circle" type="primary" text="提交"></u-button>
				</view>
			</view>
		</view>

	</view>
</template>

<script setup>
	import API from "@/api/index.js"
	import {
		reactive,
		ref
	} from "vue";
	import {
		onShow,
	} from '@dcloudio/uni-app';
	import {
		HTTP_REQUEST_URL,HTTP_PIC_URL
	} from "@/config/app.js"
	let userInfo = reactive({
		backImage: '',
		frontImage: '',
		name: '',
		number: '',
		validTo: ''
	})
	let sfzzm = ref('../../static/images/sfzzm.jpg')
	let sfzfm = ref('../../static/images/sfzfm.jpg')

	let dataZm = reactive({})
	let dataFm = reactive({})

	const emits = defineEmits('next')
	const loading = ref(false)
	const uploadList = reactive([])

	onShow(() => {
		if (uni.getStorageSync('idAuth').frontImage) {
			// 第一次认证后 从本地存储获取到的信息
			userInfo = Object.assign(userInfo, uni.getStorageSync('idAuth'))
			sfzzm.value = userInfo.frontImage
			sfzfm.value = userInfo.backImage
		} else if (uni.getStorageSync('userInfo').id && uni.getStorageSync('userInfo').idIsAudit) {
			// 已经认证过 从登录接口获取到的信息
			console.log("已认证过");
			const user = uni.getStorageSync('userInfo')
			userInfo.name = user.userName
			userInfo.number = user.cardNo
			userInfo.validTo = user.idExpireDate
			userInfo.backImage = user.idBackImg
			userInfo.frontImage = user.idFrontImg
			userInfo.portraitImage = user.portraitImage
			sfzzm.value = user.idBackImg
			sfzfm.value = user.idFrontImg
		}
	})

	// 选择图片
	const afterRead = async (event, type) => {
		console.log("afterRead step111 选择图片", event, type);
		// loading.value = true
		uploadList[type] = [{
			...event.file[0],
			status: 'uploading',
			message: '上传中'
		}]
		await uni.uploadFile({
			url: HTTP_REQUEST_URL + '/api/Recognize/UploadDriver/' + uni.getStorageSync('userInfo').id +
				'/1',
			filePath: uploadList[type][0].url,
			name: 'file',
			formData: {
				file: uploadList[type][0]
			},
			success: (uploadFileRes) => {
				const fileData = JSON.parse(uploadFileRes.data);
				console.log("uploadFileRes", fileData);
				// console.log("user",user);
				// tamperingScore：身份证PS告警分数，分数越高，PS的可能性越高
				if (fileData.data == null || fileData.data.scoreInfo.tamperingScore >= 5) {
					delete uploadList[type]
					uni.showToast({
						title: '上传身份证有误,请重新上传',
						icon: 'none'
					})
					return
				}
				// 保留有值的数据 
				const cleanObj = {};
				for (const key in fileData.data) {
					if (fileData.data[key]) {
						cleanObj[key] = fileData.data[key];
					}
				}
				console.log("cleanObj", cleanObj);
				if (cleanObj.name) {
					dataZm = cleanObj
					dataZm.frontImage = HTTP_REQUEST_URL+'/' + fileData.msg
				}
				if (cleanObj.issue) {
					dataFm = cleanObj
					dataFm.backImage = HTTP_REQUEST_URL +'/'+ fileData.msg
				}
				if (cleanObj.portraitImage) {
					dataZm.portraitImage = HTTP_REQUEST_URL+'//' + fileData.data.portraitImage
				}
				userInfo = {
					...dataZm,
					...dataFm
				}

				// if(type=='zm')userInfo.sfzzm = 'http://192.168.0.168//'+fileData.msg
				// if(type=='fm')userInfo.sfzfm = 'http://192.168.0.168//'+fileData.msg
				// for(let key in fileData.data){
				// 	console.log(userInfo[key],key,fileData.data[key]);
				// 	userInfo[key] = fileData.data[key]?fileData.data[key]:userInfo[key]
				// }]

				console.log("user auth", userInfo);
				// uni.setStorageSync('userInfo', user);
				// loading.val = false
				uploadList[type] = [{
					...uploadList[type][0],
					status: 'success',
					message: ''
				}]
			}
		})

	}
	// 删除图片
	const deletePic = (event, type) => {
		delete uploadList[type]
		if (type == 'zm') {
			for (let key in dataZm) {
				console.log("dataZm", userInfo[key]);
				delete userInfo[key]
			}
		} else if (type == 'fm') {
			for (let key in dataFm) {
				console.log("dataFm", userInfo[key]);
				delete userInfo[key]
			}
		}
	}
	const submit = async () => {
		const uploads = [this.uploadA, this.uploadB]
		const form = {
			...this.userInfo,
			url: []
		}
		uploads.forEach(item => {
			this.uploadFilePromise(item[0]).then(res => {
				form.url.push(res)
			}).catch(err => {
				uni.showToast({
					title: '图片上传失败，请稍后重试',
					icon: 'none',
					duration: 2000
				});
				return
			})
		})
	}
	const uploadFilePromise = (event) => {
		return new Promise((resolve, reject) => {
			let a = uni.uploadFile({
				url: 'http://192.168.2.21/upload', // 仅为示例，非真实的接口地址
				filePath: event,
				name: 'file',
				formData: {},
				success: (res) => {
					setTimeout(() => {
						resolve(res.data.data)
					}, 1000)
				},
				fail: () => {
					reject()
				}
			});
		})
	}

	/* 提交 */
	const nextStep = async () => {
		if (!userInfo.frontImage || !userInfo.backImage || !userInfo.validTo) {
			uni.showToast({
				title: '请先正确上传身份证！',
				icon: 'none'
			})
			return
		}
		// 有效期是否过期
		if (+new Date(userInfo.validTo) <= +new Date()) {
			uni.showToast({
				title: '身份证有效期已过！',
				icon: 'none'
			})
			return
		}
		let id = await API.uuid()
		let user = uni.getStorageSync('userInfo')
		let data = JSON.stringify({
			// 后台修改信息 必要字段------------------
			Id: user.id ? user.id : id.data,
			// Id:id.data,
			RegisterUserId: user.id,
			RegisterDeptId: user.deptId,
			RegisteTime: user.registeTime,
			editUserId: userInfo.id,
			EditTime: +new Date(),
			RegisterInfo: null,
			EditUserInfo: null,
			RegisterDept: null,
			// --------------------------
			IDBackImg: userInfo.backImage,
			IDFrontImg: userInfo.frontImage,
			portraitImage: userInfo.portraitImage,
			IDExpireDate: userInfo.validTo,
			CardNo: userInfo.number,
			UserName: userInfo.name,
			GradeId: user.gradeId,
			RefId: '',
			UserEmail: '',
			Phone: user.phone,
			Province: '',
			City: '',
			Area: uni.getStorageSync('location').city,
			Address: userInfo.address,
			Password: '',
			Lat: uni.getStorageSync('location').lat,
			Lng: uni.getStorageSync('location').lng,
			IDIsAudit: true,
			DeptId: user.deptId,
			WxOpenId: '',
			AlPayOpenId: '',
			RoleId: '',
			Balance: 0,
			OilCoin: uni.getStorageSync('uesrInfo').oilCoin,
			// OilCoin: 0,
			Takes: 0,
			IsWork: false,
			WithdrawalPassword: '',
			LastIp: '',
			LastTime: user.lastTime,
			ClentSys: '',
			ClentMessageId: '',
			IsOnline: true
		})
		console.log(userInfo.gradeId, data);
		let res = await API.User(data)
		console.log("提交 idAuth", res, data);
		uni.showToast({
			title: "添加成功",
			icon: 'none'
		})
		let cleanObj = {};
		for (const key in userInfo) {
			if (userInfo[key]) {
				cleanObj[key] = userInfo[key];
			}
		}
		uni.setStorageSync('idAuth', cleanObj)
		setTimeout(() => {
			uni.switchTab({
				url: '/pages/mine/mine'
			})
		}, 500)

		// emits('next', 1)

	}
</script>

<style lang="scss">
	.ithui {

		&-content {
			.upload {
				display: flex;
				justify-content: space-between;
				flex-wrap: wrap;
				padding: 0 25rpx;
				background-color: #fff;

				&-tip {
					padding: 10rpx 0;
					font-size: 14px;
					color: #999;
				}

				&-item {
					width: 310rpx;
					padding: 20rpx;
					text-align: center;

					.title {
						color: #999;
						font-size: 28rpx;
						line-height: 28rpx;
					}
				}
			}

			.confirm {
				.tips {
					color: #999;
					font-weight: normal;
					font-size: 32rpx;
					padding: 30rpx;
					background-color: #fff;
				}

				&-item {
					display: -webkit-box;
					display: -webkit-flex;
					display: flex;
					-webkit-box-align: center;
					-webkit-align-items: center;
					align-items: center;
					padding: 25rpx 30rpx;
					position: relative;
					background-color: #fff;

					.key {
						-webkit-box-flex: 1;
						-webkit-flex: 1;
						flex: 1;
						min-width: 0;
						font-size: 28rpx;
						color: #333;
						// font-weight: bold;
					}

					.val {}
				}

				.b-line {
					position: relative;

					&:after {
						content: '';
						position: absolute;
						z-index: 2;
						bottom: 0;
						left: 0;
						width: 100%;
						height: 2rpx;
						border-bottom: 2rpx solid #e2e2e2;
						transform: scaleY(0.5);
						transform-origin: 0 100%;
						-webkit-transform: scaleY(0.5);
						-webkit-transform-origin: 0 100%;
					}
				}
			}

			.submit {
				position: fixed;
				width: 90%;
				bottom: 0;
				padding: 20px;
			}
		}
	}
</style>